package com.asggo.g21.controller;

import com.asggo.g21.utils.SseEmitterUtil;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * Created by IntelliJ IDEA.
 *
 * @author eric 2024/3/27 11:17
 */
@Controller
@RequestMapping("/sse")
public class SseController {

  /**
   * 创建连接. "text/event-stream; charset=utf-8"
   *
   * @param userId 标识客户端.
   * @return SseEmitter.
   */
  @PostMapping(value = "/connect/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  public SseEmitter connect(@PathVariable String userId) {
    return SseEmitterUtil.connect(userId);
  }

  @PostMapping("/send/{userId}")
  public ResponseEntity<Void> send(@PathVariable String userId, @RequestParam String message) {
    SseEmitterUtil.sendMessage(userId, message);
    return ResponseEntity.ok().build();
  }

  @PostMapping("/send/all")
  public ResponseEntity<Void> sendAll(@RequestParam String message) {
    SseEmitterUtil.publishAll(message);
    return ResponseEntity.ok().build();
  }
}
